//
//  ZBWebViewController.m
//  ZBCooking
//
//  Created by xzb on 2019/2/18.
//  Copyright © 2019 xzb. All rights reserved.
//

#import "ZBWebViewController.h"
#import <WebKit/WebKit.h>
#import <WebViewJavascriptBridge.h>

@interface ZBWebViewController ()<WKScriptMessageHandler, WKNavigationDelegate, WKUIDelegate>

@property (nonatomic, copy) NSString *URLStr;
@property (nonatomic, strong) WKWebView *webView;
@property (strong, nonatomic) UIProgressView *progressView;
@property (copy, nonatomic) NSString *urlStr;

@property (copy, nonatomic) NSString *askUrl;

@end

@implementation ZBWebViewController
- (BOOL)canOpenControllerWithParams:(NSDictionary *)params
{
    NSDictionary *info = params[ZBRouterParameterUserInfo];
    if (![info.allKeys containsObject:@"url"]) {
        Log(@"url is empty");
        return NO;
    }
    self.URLStr = info[@"url"];
    return YES;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    
    WKWebViewConfiguration *config = [[WKWebViewConfiguration alloc] init];
    config.preferences = [[WKPreferences alloc] init];
    config.preferences.minimumFontSize = 10;
    config.preferences.javaScriptCanOpenWindowsAutomatically = NO;
    config.userContentController = [[WKUserContentController alloc] init];
    
    self.webView = [[WKWebView alloc] initWithFrame:CGRectZero configuration:config];
    self.webView.navigationDelegate = self;
    self.webView.UIDelegate = self;
    [self.view addSubview:self.webView];
    [self.webView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.bottom.offset(0);
        make.top.equalTo(self.navigationBar.mas_bottom);
    }];
    if (self.URLStr.length > 0) {
        [self.webView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:self.URLStr]]];
    }
    
    [self.webView addObserver:self
                   forKeyPath:@"loading"
                      options:NSKeyValueObservingOptionNew
                      context:nil];
    [self.webView addObserver:self
                   forKeyPath:@"title"
                      options:NSKeyValueObservingOptionNew
                      context:nil];
    [self.webView addObserver:self
                   forKeyPath:@"estimatedProgress"
                      options:NSKeyValueObservingOptionNew
                      context:nil];
    [self.webView addObserver:self
                   forKeyPath:@"canGoBack"
                      options:NSKeyValueObservingOptionNew
                      context:nil];
    
    [self creatProgressView];
}

- (void)creatProgressView
{
    self.progressView = [[UIProgressView alloc] init];
    self.progressView.backgroundColor = [UIColor clearColor];
    self.progressView.trackTintColor = [UIColor clearColor];
    self.progressView.progressTintColor = [UIColor greenColor];
    [self.view addSubview:self.progressView];
    [self.view bringSubviewToFront:self.progressView];
    [self.progressView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.offset(0);
        make.top.offset(self.navigationBarBottom);
    }];
}

- (void)dealloc
{
    [self.webView removeObserver:self forKeyPath:@"loading"];
    [self.webView removeObserver:self forKeyPath:@"title"];
    [self.webView removeObserver:self forKeyPath:@"estimatedProgress"];
    [self.webView removeObserver:self forKeyPath:@"canGoBack"];
}
#pragma mark WKScriptMessageHandler  js调用oc触发事件
- (void)userContentController:(WKUserContentController *)userContentController
      didReceiveScriptMessage:(WKScriptMessage *)message
{
    Log(@"<JS调用了 %@ 方法,参数:%@>", message.name, message.body);
}

#pragma mark WKNavigationDelegate
- (void)webView:(WKWebView *)webView decidePolicyForNavigationAction:(WKNavigationAction *)navigationAction decisionHandler:(void (^)(WKNavigationActionPolicy))decisionHandler
{
    if ([navigationAction.request.URL.scheme containsString:@"app-settings"]) {
        [[UIApplication sharedApplication] openURL:[NSURL URLWithString:UIApplicationOpenSettingsURLString]];
    }
    
    self.askUrl = navigationAction.request.URL.absoluteString;
    self.progressView.alpha = 1.0;
    decisionHandler(WKNavigationActionPolicyAllow);
}
- (void)webView:(WKWebView *)webView didFailProvisionalNavigation:(null_unspecified WKNavigation *)navigation withError:(NSError *)error;
{
    
    
}
- (void)webView:(WKWebView *)webView didFailNavigation:(null_unspecified WKNavigation *)navigation withError:(NSError *)error;
{
    
}
#pragma mark - kvo
- (void)observeValueForKeyPath:(NSString *)keyPath
                      ofObject:(id)object
                        change:(NSDictionary<NSString *, id> *)change
                       context:(void *)context
{
    
    if ([keyPath isEqualToString:@"canGoBack"])
    {
    }
    
    if ([keyPath isEqualToString:@"loading"])
    {
    }
    else if ([keyPath isEqualToString:@"title"])
    {
        self.title = self.webView.title;
    }
    else if ([keyPath isEqualToString:@"estimatedProgress"])
    {
        self.progressView.progress = self.webView.estimatedProgress;
    }
    
    if (!self.webView.loading)
    {
        [UIView animateWithDuration:0.5f
                         animations:^{
                             self.progressView.alpha = 0;
                         }];
    }
}

@end
